package com.tuling.controller;


import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/v2")
public class UploadV2Controller {

    private Map<String, Set<Integer>> cache = new HashMap<String,  Set<Integer>>();
    private final static String utf8 ="utf-8";

    @PostMapping("/upload")
    @ResponseBody
    public String upload(HttpServletRequest request) throws Exception {

        //分片
        MultipartHttpServletRequest multipartRequest=((MultipartHttpServletRequest) request);
        List<MultipartFile> files = multipartRequest.getFiles("upload");
        // 1. 如果FileItem表示表单字段，则取根据字段名chunk、chunks、name，取出对应的字段值
        Integer chunk = Integer.valueOf(multipartRequest.getParameter("chunk"));
        Integer chunks = Integer.valueOf(multipartRequest.getParameter("chunks"));;
        String name = multipartRequest.getParameter("name");
        String id =  multipartRequest.getParameter("id");
        String uploadPath = "F:\\fileItem";
        BufferedOutputStream os = null;

        try{
            for(MultipartFile item : files){
                // 2. 如果FileItem表示表示一个文件
                String temFileName = name;
                if(name != null){
                    // 如果有分片，文件名为：分片索引-文件名
                    if(chunk != null){
                        temFileName = chunk +"_"+name;
                    }
                    // 创建一个文件临时文件，将内容写入临时文件
                    File temFile = new File(uploadPath,temFileName);
                    if(!temFile.exists()){//断点续传
                        FileUtils.writeByteArrayToFile(temFile, item.getBytes());
                    }

                }
            }
            //3. 如果有分片chunk，并且分片chunk刚好等于最后一个分片(总分片数-1)，则进行文件合并
            if( chunk != null && (chunk.intValue() == chunks.intValue()-1) ){
                File file = new File(uploadPath,name);
                os = new BufferedOutputStream(new FileOutputStream(file));
                // 逐一取出分片1，分片2...进行写入到最终的输出流中，并且删除分片
                for(int i = 0; i < chunks; i++){
                    File tempFile = new File(uploadPath,i+"_"+name);
                    while(!tempFile.exists()){
                        Thread.sleep(100);
                    }
                    byte[] bytes = FileUtils.readFileToByteArray(tempFile);
                    os.write(bytes);
                    os.flush();
                    tempFile.delete();
                }
                os.flush();
            }
            /*if (id != null){
                Set<Integer> finishChunks = cache.get(id);
                if (finishChunks == null){
                    finishChunks = new HashSet<>();
                }
                finishChunks.add(chunk);
                cache.put(id, finishChunks);
            }*/
            return "上传成功"+name;

        }finally {
            try{
                if(os != null){
                    os.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /*@RequestMapping("/query")
    @ResponseBody
    public ApiResult query(String id) throws Exception {
        Set<Integer> finishChunks = cache.get(id);
        return new ApiResult.Builder().success(finishChunks).build();
    }*/
}
